# -*- coding: utf-8 -*-

from odoo import models, fields, api


class hiwprint(models.Model):
    _name = 'hiwprint.hiwprint'
    _description = 'hiwprint.hiwprint'

    name = fields.Char()
    ziduans = fields.Char()
    moban = fields.Char()
    moxing = fields.Many2one('ir.model' )
    jihuo=fields.Boolean("激活")
    report_id=fields.Many2one('ir.actions.report')
    moxing_model_name = fields.Char(
        string='模型技术名',
        related='moxing.model',
        store=True,
        readonly=True
    )

    @api.model
    def create(self, vals):
        record = super().create(vals)
        record._sync_report_record()
        return record

    def write(self, vals):
        res = super().write(vals)
        if 'jihuo' in vals or 'name' in vals or 'moxing' in vals:
            self._sync_report_record()
        return res

    def unlink(self):
        self._delete_report_record()
        return super().unlink()

    def _sync_report_record(self):
        for record in self:
            if record.jihuo:
                # 激活时自动创建 report 动作
                if not record.report_id:
                    report_vals = {
                        'name': record.name or 'HiwPrint Report',
                        'binding_model_id': record.moxing.id,
                        'model': record.moxing.model,
                        'report_type': 'abcd',  # 或其它类型
                        'report_name': f'abcd.{record.name.lower().replace(" ", "_")}',
                        'report_file': '',  # 可选字段
                    }
                    report = self.env['ir.actions.report'].create(report_vals)
                    record.report_id = report.id
            else:
                # 取消激活则删除 report 动作
                if record.report_id:
                    record.report_id.unlink()
                    record.report_id = False

    def _delete_report_record(self):
        for record in self:
            if record.report_id:
                record.report_id.unlink()

